import json
from http import HTTPStatus
from typing import Optional, Any
from dataclasses import asdict
from pydantic import BaseModel
from code.app.config.exception import ResponseExceptionEnum
from code.app.config.middleware import request_id_context
from code.app.services.api_response import APIResponse


class Response(BaseModel):
    code: int
    message: str
    data: Any
    request_id: str

    def __str__(self) -> str:
        return json.dumps(asdict(self), ensure_ascii=False)

    @staticmethod
    def success(data: Optional[Any] = None) -> 'Response':
        """生成成功的响应"""
        # 从上下文变量获取请求 ID
        request_id = request_id_context.get("request_id")
        return Response(
            code=0,
            message="",
            data=data,
            request_id=request_id
        )

    @staticmethod
    def fail(error: ResponseExceptionEnum, data: Optional[Any] = None) -> 'Response':
        """生成失败的响应"""
        # 从上下文变量获取请求 ID
        request_id = request_id_context.get("request_id")
        return Response(
            code=error.code,
            message=error.message,
            data=data,
            request_id=request_id
        )

    @staticmethod
    def from_response(api_response: APIResponse) -> 'Response':
        """类型转换
        将 APIResponse 转化为 Response
        """
        if api_response.status_code != HTTPStatus.OK or (api_response.message and api_response.message.strip()):
            error = ResponseExceptionEnum.API_CALL_ERROR
            if api_response.message is not None:
                error.modify_message(api_response.message)
            response = Response.fail(error=error, data=api_response)
            return response

        return Response.success(data=api_response)
